package comm;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serializer {

	final private static Serializer instance = new Serializer();
	private Serializer(){

	}

	public static Serializer getInstance(){
		return instance;
	}

	public byte[] serialize (Serializable object) throws IOException{
		//turns an object implementing Serializable to bytes 
		// Serialize to a byte array
	    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
	    ObjectOutput out = new ObjectOutputStream(bos) ;
	    out.writeObject(object);
	    out.close();

	    // Get the bytes of the serialized object
	    byte[] bytes = bos.toByteArray();
	    
		return bytes;
	}
	public Serializable deserialize (byte[] bytes) throws IOException, ClassNotFoundException{
		//turns a flattened, Serializable object represented as bytes back into the object
		
	    // Deserialize from a byte array
		ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
	    Object object = in.readObject();
	    in.close();
		
		Serializable serial = null;
		if (object instanceof Serializable){
			serial = (Serializable) object;
		}
		
		return serial;
	}


}
